package com.netty.rpc.spring;

import com.netty.rpc.annotation.RpcReference;
import com.netty.rpc.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SpringBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> sourceBean = bean.getClass();
        Field[] fields = sourceBean.getDeclaredFields();
        for(Field field : fields){
            field.setAccessible(true);
            RpcReference rpcReference = field.getAnnotation(RpcReference.class);
            if(rpcReference != null){
                RpcClientProxy rpcClientProxy = new RpcClientProxy();
                Object proxyBean = rpcClientProxy.getRpcClientProxy(field.getType());
                try {
                    field.set(bean, proxyBean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
